import { Modal, Upload, message, Button } from 'antd'
import React, { useState } from 'react'
import { PlusOutlined } from '@ant-design/icons'
import { baseURL } from '@/api/config'

import style from './index.module.scss'
type props = {
  off: () => void
  show: boolean
  upCover: (url: string) => void
}
export default ({ off, show, upCover }: props) => {
  const [loading, setLoading] = useState(false)
  const [imgurl, setImgurl] = useState('')
  const confirm = () => {
    upCover(imgurl)
    off()
  }
  const onChange = (info: any) => {
    const upStatus = info.file.status
    switch (upStatus) {
      case 'uploading': //上传中
        return setLoading(true)
      case 'done': //已完成
        const {
          status,
          msg,
          data: { imgurl },
        } = info.file.response
        if (!status) {
          return message.warn(msg)
        }
        setImgurl(imgurl)
        setLoading(false)
        return
      default:
        console.log(info)
        return message.warn(`上传图片系统出错 upStatus:${upStatus}`)
    }
  }
  const reset = (e: any) => {
    e.preventDefault()
    setImgurl('')
    setLoading(false)
  }
  const beforeUpload = (file: any) => {
    const isJpgOrPng =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/gif'
    if (!isJpgOrPng) {
      message.error('文件类型错误,只允许上传JPG,PNG,GIF.')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片不能超过2MB')
    }
    return isJpgOrPng && isLt2M
  }
  return (
    <Modal visible={show} onCancel={off} onOk={confirm} title="上传封面">
      <div className={style.row}>
        {loading && <div className={style.loading}>加载中...</div>}
        <Upload.Dragger
          name="coverImg"
          listType="picture-card"
          className={style.uploader}
          showUploadList={false}
          action={`${baseURL}upDateImage`}
          beforeUpload={beforeUpload}
          onChange={onChange}
        >
          {imgurl ? (
            <img src={imgurl} alt="avatar" style={{ width: '100%' }} />
          ) : (
            <PlusOutlined />
          )}
        </Upload.Dragger>
      </div>

      {imgurl && (
        <Button type="primary" style={{ marginTop: '10px' }} onClick={reset}>
          重置
        </Button>
      )}
    </Modal>
  )
}
